require('dotenv').config();
const Joi = require('joi');

// 配置验证模式
const configSchema = Joi.object({
  // 服务器配置
  server: Joi.object({
    port: Joi.number().default(3000),
    env: Joi.string().valid('development', 'production', 'test').default('development'),
    host: Joi.string().default('localhost'),
    baseUrl: Joi.string().uri().default('http://localhost:3000'),
    corsOrigins: Joi.array().items(Joi.string()).default(['*']),
    rateLimitWindow: Joi.number().default(15 * 60 * 1000), // 15 minutes
    rateLimitMax: Joi.number().default(100)
  }).default(),

  // 数据库配置
  database: Joi.object({
    host: Joi.string().required(),
    port: Joi.number().default(3306),
    name: Joi.string().required(),
    user: Joi.string().required(),
    password: Joi.string().required(),
    ssl: Joi.boolean().default(false),
    pool: Joi.object({
      max: Joi.number().default(10),
      min: Joi.number().default(0),
      acquire: Joi.number().default(30000),
      idle: Joi.number().default(10000),
      evict: Joi.number().default(1000)
    }).default()
  }).required(),

  // JWT配置
  jwt: Joi.object({
    secret: Joi.string().min(32).required(),
    expiresIn: Joi.string().default('24h'),
    refreshExpiresIn: Joi.string().default('7d'),
    issuer: Joi.string().default('managex'),
    algorithm: Joi.string().valid('HS256', 'HS384', 'HS512').default('HS256')
  }).required(),

  // 微信配置
  wechat: Joi.object({
    appId: Joi.string().required(),
    appSecret: Joi.string().required(),
    token: Joi.string(),
    encodingAESKey: Joi.string()
  }).required(),

  // 支付配置
  payment: Joi.object({
    alipay: Joi.object({
      appId: Joi.string().required(),
      privateKey: Joi.string().required(),
      publicKey: Joi.string().required(),
      sandbox: Joi.boolean().default(false)
    }).required(),
    wechatPay: Joi.object({
      mchId: Joi.string().required(),
      key: Joi.string().required(),
      certPath: Joi.string(),
      keyPath: Joi.string(),
      sandbox: Joi.boolean().default(false)
    }).required()
  }).required(),

  // 地图配置
  maps: Joi.object({
    tencent: Joi.string(),
    amap: Joi.string(),
    tianditu: Joi.string()
  }).default(),

  // Redis配置
  redis: Joi.object({
    host: Joi.string().default('localhost'),
    port: Joi.number().default(6379),
    password: Joi.string().allow('').default(''),
    db: Joi.number().default(0),
    keyPrefix: Joi.string().default('managex:'),
    ttl: Joi.number().default(86400) // 24 hours
  }).default(),

  // 邮件配置
  email: Joi.object({
    host: Joi.string().required(),
    port: Joi.number().default(587),
    secure: Joi.boolean().default(false),
    user: Joi.string().required(),
    password: Joi.string().required(),
    from: Joi.string().email().required(),
    replyTo: Joi.string().email()
  }).required(),

  // 短信配置
  sms: Joi.object({
    accessKeyId: Joi.string().required(),
    secretAccessKey: Joi.string().required(),
    signName: Joi.string().required()
  }).required(),

  // 极光推送配置
  jpush: Joi.object({
    appKey: Joi.string().required(),
    masterSecret: Joi.string().required()
  }).required(),

  // 存储配置
  storage: Joi.object({
    provider: Joi.string().valid('local', 's3', 'minio').default('local'),
    local: Joi.object({
      path: Joi.string().default('./uploads')
    }).default(),
    s3: Joi.object({
      accessKeyId: Joi.string(),
      secretAccessKey: Joi.string(),
      region: Joi.string(),
      bucket: Joi.string()
    }).default(),
    minio: Joi.object({
      endPoint: Joi.string(),
      port: Joi.number(),
      useSSL: Joi.boolean().default(true),
      accessKey: Joi.string(),
      secretKey: Joi.string(),
      bucket: Joi.string()
    }).default()
  }).default()
}).required();

// 从环境变量构建配置对象
const config = {
  server: {
    port: process.env.PORT,
    env: process.env.NODE_ENV,
    host: process.env.HOST,
    baseUrl: process.env.BASE_URL,
    corsOrigins: process.env.CORS_ORIGINS ? process.env.CORS_ORIGINS.split(',') : undefined,
    rateLimitWindow: process.env.RATE_LIMIT_WINDOW,
    rateLimitMax: process.env.RATE_LIMIT_MAX
  },
  database: {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    name: process.env.DB_NAME,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    ssl: process.env.DB_SSL === 'true',
    pool: {
      max: process.env.DB_POOL_MAX,
      min: process.env.DB_POOL_MIN,
      acquire: process.env.DB_POOL_ACQUIRE,
      idle: process.env.DB_POOL_IDLE,
      evict: process.env.DB_POOL_EVICT
    }
  },
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: process.env.JWT_EXPIRES_IN,
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN,
    issuer: process.env.JWT_ISSUER,
    algorithm: process.env.JWT_ALGORITHM
  },
  wechat: {
    appId: process.env.WECHAT_APP_ID,
    appSecret: process.env.WECHAT_APP_SECRET,
    token: process.env.WECHAT_TOKEN,
    encodingAESKey: process.env.WECHAT_ENCODING_AES_KEY
  },
  payment: {
    alipay: {
      appId: process.env.ALIPAY_APP_ID,
      privateKey: process.env.ALIPAY_PRIVATE_KEY,
      publicKey: process.env.ALIPAY_PUBLIC_KEY,
      sandbox: process.env.ALIPAY_SANDBOX === 'true'
    },
    wechatPay: {
      mchId: process.env.WECHAT_PAY_MCH_ID,
      key: process.env.WECHAT_PAY_KEY,
      certPath: process.env.WECHAT_PAY_CERT_PATH,
      keyPath: process.env.WECHAT_PAY_KEY_PATH,
      sandbox: process.env.WECHAT_PAY_SANDBOX === 'true'
    }
  },
  maps: {
    tencent: process.env.TENCENT_MAP_KEY,
    amap: process.env.AMAP_KEY,
    tianditu: process.env.TIANDITU_KEY
  },
  redis: {
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    password: process.env.REDIS_PASSWORD,
    db: process.env.REDIS_DB,
    keyPrefix: process.env.REDIS_KEY_PREFIX,
    ttl: process.env.REDIS_TTL
  },
  email: {
    host: process.env.EMAIL_HOST,
    port: process.env.EMAIL_PORT,
    secure: process.env.EMAIL_SECURE === 'true',
    user: process.env.EMAIL_USER,
    password: process.env.EMAIL_PASSWORD,
    from: process.env.EMAIL_FROM,
    replyTo: process.env.EMAIL_REPLY_TO
  },
  sms: {
    accessKeyId: process.env.SMS_ACCESS_KEY_ID,
    secretAccessKey: process.env.SMS_SECRET_ACCESS_KEY,
    signName: process.env.SMS_SIGN_NAME
  },
  jpush: {
    appKey: process.env.JPUSH_APP_KEY,
    masterSecret: process.env.JPUSH_MASTER_SECRET
  },
  storage: {
    provider: process.env.STORAGE_PROVIDER,
    local: {
      path: process.env.STORAGE_LOCAL_PATH
    },
    s3: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
      region: process.env.AWS_REGION,
      bucket: process.env.AWS_BUCKET
    },
    minio: {
      endPoint: process.env.MINIO_ENDPOINT,
      port: process.env.MINIO_PORT,
      useSSL: process.env.MINIO_USE_SSL === 'true',
      accessKey: process.env.MINIO_ACCESS_KEY,
      secretKey: process.env.MINIO_SECRET_KEY,
      bucket: process.env.MINIO_BUCKET
    }
  }
};

// 验证配置
const { error, value: validatedConfig } = configSchema.validate(config, {
  abortEarly: false,
  allowUnknown: true
});

if (error) {
  console.error('Configuration validation error:');
  error.details.forEach((detail) => {
    console.error(`- ${detail.message}`);
  });
  process.exit(1);
}

// 确保敏感配置不会被意外暴露
Object.defineProperties(validatedConfig, {
  'database.password': {
    enumerable: false,
    configurable: false
  },
  'jwt.secret': {
    enumerable: false,
    configurable: false
  },
  'wechat.appSecret': {
    enumerable: false,
    configurable: false
  },
  'payment.alipay.privateKey': {
    enumerable: false,
    configurable: false
  },
  'payment.wechatPay.key': {
    enumerable: false,
    configurable: false
  }
});

module.exports = validatedConfig; 